package com.ai.study.dashscope.controller.prompt;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * @Author chenwei
 * @Date 2025/5/27 11:23
 */
@RestController
@RequestMapping("/dashscope/example/ai")
@Tag(name = "prompt Role 测试")
public class PromptRoleController {

    private final ChatClient dashScopeChatClient;

    /**
     * 加载 System prompt tmpl.
     */
    @Value("classpath:/dashscope/prompts/system-message.st")
    private Resource systemResource;

    public PromptRoleController(@Value("classpath:/dashscope/prompts/system-message.st") Resource myResource,
                                @Qualifier("dashScopeChatClient") ChatClient dashScopeChatClient) {
        this.systemResource = myResource;
        this.dashScopeChatClient = dashScopeChatClient;
    }

    @GetMapping("/roles")
    @Operation(summary = "模版中配置系统提示词（SystemPromptTemplate）")
    public Flux<String> generate(
            @RequestParam(
                    value = "message",
                    required = false,
                    defaultValue = "Tell me about three famous pirates from the Golden Age of Piracy and " +
                            "why they did.  Write at least a sentence for each pirate.") String message,
            @RequestParam(value = "name", required = false, defaultValue = "Bob") String name,
            @RequestParam(value = "voice", required = false, defaultValue = "pirate") String voice
    ) {

        // 用户输入
        UserMessage userMessage = new UserMessage(message);

        // 使用 System prompt tmpl
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
        // 填充 System prompt 中的变量值
        Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));

        // 调用大模型
        return dashScopeChatClient.prompt(
                        new Prompt(
                                List.of(userMessage, systemMessage)
                        )
                ).stream().content();
    }
}